package 二叉树;

import java.util.*;

/**
 * https://leetcode-cn.com/problems/binary-tree-postorder-traversal/
 */
public class _145_二叉树的后序遍历 {

    /**
     * 树的后序遍历“左右根”，先序遍历是“根左右”，我们可以把树的先序代码改成根右左（在代码中体现就是更改左右子节点入栈顺序），最后将根右左的遍历顺序反转。
     * 举个例子
     *      1
     *    / \
     *   2   3
     *  / \ /
     * 4 5 6
     * 根左右：124536
     * 根右左：136254
     * 左右根：452631
     *
     */
    List<Integer> list = new ArrayList<>();
    public List<Integer> postorderTraversal(TreeNode root) {
        if (root == null) return list;

        Stack<TreeNode> stack = new Stack<>();
        TreeNode node = root;
        stack.push(node);
        while (!stack.isEmpty()) {
                node = stack.pop();
                list.add(node.val);
                if (node.left !=null) stack.push(node.left);
                if (node.right !=null) stack.push(node.right);
        }
        Collections.reverse(list);
        return list;
    }


    /**
     * https://leetcode-cn.com/problems/binary-tree-postorder-traversal/solution/er-cha-shu-de-hou-xu-bian-li-by-leetcode-solution/
     * @param root
     * @return
     */
     public List<Integer> postorderTraversal1(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        if (root == null) {
            return res;
        }

        Deque<TreeNode> stack = new LinkedList<TreeNode>();
        TreeNode prev = null;
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            if (root.right == null || root.right == prev) {
                res.add(root.val);
                prev = root;
                root = null;
            } else {
                stack.push(root);
                root = root.right;
            }
        }
        return res;
    }

}
